/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.meanzoft.m3d.model.mdx;

/**
 *
 * @author Meanz
 */
public class ByteStream {

    private byte[] caret;
    private int offset = 0;

    public ByteStream(byte[] caret) {
        this.caret = caret;
    }

    public byte[] getCaret() {
        return caret;
    }

    public void setCaret(byte[] caret) {
        this.caret = caret;
    }

    public int getOffset() {
        return offset;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }

    public void skip(int skip) {
        offset += skip;
    }

    public int getRemaining() {
        return caret.length - offset;
    }

    /**
     * Read
     */
    public byte get() {
        return caret[offset++];
    }

    public byte[] get(int len) {
        byte[] b = new byte[len];
        for (int i = 0; i < b.length; i++) {
            b[i] = get();
        }
        return b;
    }

    public final byte[] get(final byte[] b) {
        for (int i = 0; i < b.length; i++) {
            b[i] = get();
        }
        return b;
    }

    public int getLEDWORD() {
        skip(4);
        return (caret[offset - 1] & 0xff) << 24
                | (caret[offset - 2] & 0xff) << 16
                | (caret[offset - 3] & 0xff) << 8
                | (caret[offset - 4] & 0xff);

    }

    public int getWord() {
        skip(2);
        return (caret[offset - 1] & 0xff) >> 8
                | (caret[offset - 2] & 0xff);
    }

    public int getDWORD() {
        if (true) {
            return getLEDWORD();
        }
        skip(4);
        return (caret[offset - 1] & 0xff) >> 24
                | (caret[offset - 2] & 0xff) >> 16
                | (caret[offset - 3] & 0xff) >> 8
                | (caret[offset - 4] & 0xff);
    }

    public float getFloat() {
        return Float.intBitsToFloat(getLEDWORD());
    }

    public String getString(int length) {
        String str = "";
        if (length != 0) {
            byte[] temp = new byte[length];
            for (int i = 0; i < temp.length; i++) {
                temp[i] = get();
            }
            str = new String(temp);
        } else {
            while (getRemaining() > 0 && caret[offset] != '\0') {
                str += (char) get();
            }
        }
        if (str == "") {
            str = null;
        }
        return str;

    }
    /**
     * Write
     */
}
